package jnpf.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.UserInfo;
import jnpf.config.PermissionsConfig;
import jnpf.entity.ZXGL_LiXiangGuanLiEntity;
import jnpf.entity.ZXGL_XiangMuLiXiang_MingXiEntity;
import jnpf.mapper.ZXGL_LiXiangGuanLiMapper;
import jnpf.mapper.ZXGL_XiangMuLiXiang_MingXiMapper;
import jnpf.model.zxgl_lixiangguanli.ZXGL_LiXiangGuanLiPagination;
import jnpf.permission.service.AuthorizeService;
import jnpf.service.ZXGL_LiXiangGuanLiService;
import jnpf.service.ZXGL_XiangMuLiXiang_MingXiService;
import jnpf.util.DateUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.*;

/**
 * ZXGL_LiXiangGuanLi
 * 版本： V2.0
 * 版权： 河北交投智能交通技术有限责任公司
 * 作者： 数字交投项目组
 * 日期： 2025-03-17
 */
@Service
public class ZXGL_LiXiangGuanLiServiceImpl extends ServiceImpl<ZXGL_LiXiangGuanLiMapper, ZXGL_LiXiangGuanLiEntity> implements ZXGL_LiXiangGuanLiService {


    private static final Logger logger = LoggerFactory.getLogger(ZXGL_LiXiangGuanLiServiceImpl.class);

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private ZXGL_XiangMuLiXiang_MingXiService zXGL_XiangMuLiXiang_MingXiService;

    @Autowired
    private ZXGL_XiangMuLiXiang_MingXiMapper zxgl_xiangMuLiXiang_mingXiMapper;

    @Resource
    PermissionsConfig permissionsConfig;

    @Autowired
    private AuthorizeService authorizeService;

    @Override
    public List<ZXGL_LiXiangGuanLiEntity> getList(ZXGL_LiXiangGuanLiPagination zXGL_LiXiangGuanLiPagination) {

        List<String> AllIdList = new ArrayList();
        int total = 0;
        QueryWrapper<ZXGL_LiXiangGuanLiEntity> zXGL_LiXiangGuanLiQueryWrapper = new QueryWrapper<>();
        QueryWrapper<ZXGL_XiangMuLiXiang_MingXiEntity> zXGL_XiangMuLiXiang_MingXiQueryWrapper = new QueryWrapper<>();
        //TODO 增加权限逻辑
        UserInfo userInfo = userProvider.get();
        if (!userInfo.getIsAdministrator()) {
            String alldataRoleId = permissionsConfig.getAlldataRoleid();
            List<String> roleIds = userInfo.getRoleIds();
            if (roleIds == null || (StringUtils.isNotBlank(alldataRoleId) && !roleIds.contains(alldataRoleId))) {
                //立项管理：创建人看本人数据；创建人部门负责人看本部门数据；创建人部门主管领导看所管理部门数据；
                String userId = userInfo.getUserId();
                zXGL_LiXiangGuanLiQueryWrapper.lambda().and(wrapper -> wrapper
                        .eq(ZXGL_LiXiangGuanLiEntity::getDepartmentManager, userId)//部门负责人
                        .or()
                        .eq(ZXGL_LiXiangGuanLiEntity::getDepartmentHeadleader, userId) //部门主管领导
                        .or()
                        .eq(ZXGL_LiXiangGuanLiEntity::getCreatorUserId, userId));//创建人
            }
        }


        int zXGL_LiXiangGuanLiNum = 0;
        if (StringUtil.isNotEmpty(zXGL_LiXiangGuanLiPagination.getDepartmentName())) {
            zXGL_LiXiangGuanLiNum++;
            zXGL_LiXiangGuanLiQueryWrapper.lambda().eq(ZXGL_LiXiangGuanLiEntity::getDepartmentName, zXGL_LiXiangGuanLiPagination.getDepartmentName());
        }

        if (StringUtil.isNotEmpty(zXGL_LiXiangGuanLiPagination.getCreatorUser())) {
            zXGL_LiXiangGuanLiNum++;
            zXGL_LiXiangGuanLiQueryWrapper.lambda().eq(ZXGL_LiXiangGuanLiEntity::getCreatorUser, zXGL_LiXiangGuanLiPagination.getCreatorUser());
        }

        if (StringUtil.isNotEmpty(zXGL_LiXiangGuanLiPagination.getCreatorTime())) {
            zXGL_LiXiangGuanLiNum++;
            List<String> CreatorTimeList = zXGL_LiXiangGuanLiPagination.getCreatorTime();
            Long fir = Long.valueOf(CreatorTimeList.get(0));
            Long sec = Long.valueOf(CreatorTimeList.get(1));

            zXGL_LiXiangGuanLiQueryWrapper.lambda().ge(ZXGL_LiXiangGuanLiEntity::getCreatorTime, new Date(fir))
                    .le(ZXGL_LiXiangGuanLiEntity::getCreatorTime, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));

        }


        if (AllIdList.size() > 0) {
            zXGL_LiXiangGuanLiQueryWrapper.lambda().in(ZXGL_LiXiangGuanLiEntity::getId, AllIdList);
        }

        /**
         * 数据权限 此处手动写入菜单id
         */
//        String moduleId = "668007699962686661";
//        if (!userProvider.get().getIsAdministrator()) {
//            Object conditionObj = authorizeService.getCondition(zXGL_LiXiangGuanLiQueryWrapper, userProvider.get(), moduleId);
//            if (ObjectUtil.isEmpty(conditionObj)) {
//                return new ArrayList<>();
//            }
//            zXGL_LiXiangGuanLiQueryWrapper = (QueryWrapper<ZXGL_LiXiangGuanLiEntity>) authorizeService.getCondition(zXGL_LiXiangGuanLiQueryWrapper, userProvider.get(), moduleId);
//        }

        //排序
        if (StringUtil.isEmpty(zXGL_LiXiangGuanLiPagination.getSidx())) {
            zXGL_LiXiangGuanLiQueryWrapper.lambda().orderByDesc(ZXGL_LiXiangGuanLiEntity::getOrganizeName);
        } else {
            // try {
            // String sidx = zXGL_LiXiangGuanLiPagination.getSidx();
            // ZXGL_LiXiangGuanLiEntity zXGL_LiXiangGuanLiEntity = new ZXGL_LiXiangGuanLiEntity();
            // Field declaredField = zXGL_LiXiangGuanLiEntity.getClass().getDeclaredField(sidx);
            // declaredField.setAccessible(true);
            // String value = declaredField.getAnnotation(TableField.class).value();
            // zXGL_LiXiangGuanLiQueryWrapper = "asc".equals(zXGL_LiXiangGuanLiPagination.getSort().toLowerCase()) ? zXGL_LiXiangGuanLiQueryWrapper.orderByAsc(value) : zXGL_LiXiangGuanLiQueryWrapper.orderByDesc(value);
            zXGL_LiXiangGuanLiQueryWrapper = "asc".equals(zXGL_LiXiangGuanLiPagination.getSort().toLowerCase()) ? zXGL_LiXiangGuanLiQueryWrapper.orderByAsc(zXGL_LiXiangGuanLiPagination.getSidx()) : zXGL_LiXiangGuanLiQueryWrapper.orderByDesc(zXGL_LiXiangGuanLiPagination.getSidx());
            // } catch (NoSuchFieldException e) {
            // e.printStackTrace();
            // }
        }
        if ((total > 0 && AllIdList.size() > 0) || total == 0) {
            Page<ZXGL_LiXiangGuanLiEntity> page = new Page<>(zXGL_LiXiangGuanLiPagination.getCurrentPage(), zXGL_LiXiangGuanLiPagination.getPageSize());
            IPage<ZXGL_LiXiangGuanLiEntity> userIPage = this.page(page, zXGL_LiXiangGuanLiQueryWrapper);
            return zXGL_LiXiangGuanLiPagination.setData(userIPage.getRecords(), userIPage.getTotal());
        } else {
            List<ZXGL_LiXiangGuanLiEntity> list = new ArrayList();
            return zXGL_LiXiangGuanLiPagination.setData(list, list.size());
        }
    }

    @Override
    public List<ZXGL_LiXiangGuanLiEntity> getTypeList(ZXGL_LiXiangGuanLiPagination zXGL_LiXiangGuanLiPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        int total = 0;
        QueryWrapper<ZXGL_LiXiangGuanLiEntity> zXGL_LiXiangGuanLiQueryWrapper = new QueryWrapper<>();
        QueryWrapper<ZXGL_XiangMuLiXiang_MingXiEntity> zXGL_XiangMuLiXiang_MingXiQueryWrapper = new QueryWrapper<>();
        int zXGL_LiXiangGuanLiNum = 0;
        if (StringUtil.isNotEmpty(zXGL_LiXiangGuanLiPagination.getDepartmentName())) {
            zXGL_LiXiangGuanLiNum++;
            zXGL_LiXiangGuanLiQueryWrapper.lambda().eq(ZXGL_LiXiangGuanLiEntity::getDepartmentName, zXGL_LiXiangGuanLiPagination.getDepartmentName());
        }

        if (StringUtil.isNotEmpty(zXGL_LiXiangGuanLiPagination.getCreatorUser())) {
            zXGL_LiXiangGuanLiNum++;
            zXGL_LiXiangGuanLiQueryWrapper.lambda().eq(ZXGL_LiXiangGuanLiEntity::getCreatorUser, zXGL_LiXiangGuanLiPagination.getCreatorUser());
        }

        if (StringUtil.isNotEmpty(zXGL_LiXiangGuanLiPagination.getCreatorTime())) {
            zXGL_LiXiangGuanLiNum++;
            List<String> CreatorTimeList = zXGL_LiXiangGuanLiPagination.getCreatorTime();
            Long fir = Long.valueOf(CreatorTimeList.get(0));
            Long sec = Long.valueOf(CreatorTimeList.get(1));

            zXGL_LiXiangGuanLiQueryWrapper.lambda().ge(ZXGL_LiXiangGuanLiEntity::getCreatorTime, new Date(fir))
                    .le(ZXGL_LiXiangGuanLiEntity::getCreatorTime, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));

        }

        if (AllIdList.size() > 0) {
            zXGL_LiXiangGuanLiQueryWrapper.lambda().in(ZXGL_LiXiangGuanLiEntity::getId, AllIdList);
        }
        //排序
        if (StringUtil.isEmpty(zXGL_LiXiangGuanLiPagination.getSidx())) {
            zXGL_LiXiangGuanLiQueryWrapper.lambda().orderByDesc(ZXGL_LiXiangGuanLiEntity::getOrganizeName);
        } else {
            try {
                String sidx = zXGL_LiXiangGuanLiPagination.getSidx();
                ZXGL_LiXiangGuanLiEntity zXGL_LiXiangGuanLiEntity = new ZXGL_LiXiangGuanLiEntity();
                Field declaredField = zXGL_LiXiangGuanLiEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                zXGL_LiXiangGuanLiQueryWrapper = "asc".equals(zXGL_LiXiangGuanLiPagination.getSort().toLowerCase()) ? zXGL_LiXiangGuanLiQueryWrapper.orderByAsc(value) : zXGL_LiXiangGuanLiQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<ZXGL_LiXiangGuanLiEntity> page = new Page<>(zXGL_LiXiangGuanLiPagination.getCurrentPage(), zXGL_LiXiangGuanLiPagination.getPageSize());
                IPage<ZXGL_LiXiangGuanLiEntity> userIPage = this.page(page, zXGL_LiXiangGuanLiQueryWrapper);
                return zXGL_LiXiangGuanLiPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<ZXGL_LiXiangGuanLiEntity> list = new ArrayList();
                return zXGL_LiXiangGuanLiPagination.setData(list, list.size());
            }
        } else {
            return this.list(zXGL_LiXiangGuanLiQueryWrapper);
        }
    }

    @Override
    public ZXGL_LiXiangGuanLiEntity getInfo(String id) {
        QueryWrapper<ZXGL_LiXiangGuanLiEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZXGL_LiXiangGuanLiEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZXGL_LiXiangGuanLiEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZXGL_LiXiangGuanLiEntity entity) {
        entity.setId(id);
        return this.updateById(entity);
    }

    @Override
    public void delete(ZXGL_LiXiangGuanLiEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    @Override
    public void deleteXmfjzbm(String id) {
        if (!"".equals(id) || id != null) {
            this.removeById(id);
        }
    }

    @Override
    public List<String> findByName(String name, String id) {
        return zxgl_xiangMuLiXiang_mingXiMapper.findByName(name, id);
    }


    //子表方法
    @Override
    public List<ZXGL_XiangMuLiXiang_MingXiEntity> GetZXGL_XiangMuLiXiang_MingXiList(String id) {
        QueryWrapper<ZXGL_XiangMuLiXiang_MingXiEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZXGL_XiangMuLiXiang_MingXiEntity::getMainid, id);
        return zXGL_XiangMuLiXiang_MingXiService.list(queryWrapper);
    }

    @Override
    public Boolean saveLiXiangGuanLi(ZXGL_LiXiangGuanLiEntity entity) {
        return baseMapper.saveLiXiangGuanLi(entity) > 0;
    }

    //列表子表数据方法

    @Override
    public List<Map<String, Object>> parseExcel(MultipartFile file) {
        List<Map<String, Object>> dataList = new ArrayList<>();
        try (InputStream is = file.getInputStream()) {
//            Workbook workbook = new XSSFWorkbook(is);
//            Workbook workbook = WorkbookFactory.create(is);
            Workbook workbook;
            String fileName = file.getOriginalFilename();
            if (fileName != null && fileName.endsWith(".xlsx")) {
                workbook = WorkbookFactory.create(is);
            } else if (fileName != null && fileName.endsWith(".xls")) {
                workbook = WorkbookFactory.create(is);
            } else {
                throw new IllegalArgumentException("不支持的文件类型");
            }
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            for (Row row : sheet) {
                if (isRowEmpty(row)) { // 跳过空行
                    continue;
                }
                Map<String, Object> rowData = new HashMap<>();
                for (Cell cell : row) {
                    if (cell != null) {
                        int columnIndex = cell.getColumnIndex();
                        rowData.put("Column" + columnIndex, getCellValue(cell));
                    }

                }
                dataList.add(rowData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataList;
    }

    public List<Map<String, Object>> parseExcelByEasyExcel(MultipartFile file) {
        final List<Map<String, Object>> dataList = new ArrayList<>();
        // 创建一个分析监听器，用于处理每一行数据
        AnalysisEventListener<Map<Integer, String>> listener = new AnalysisEventListener<Map<Integer, String>>() {
            private List<String> headers;

            @Override
            public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                // 处理表头信息
                headers = new ArrayList<>();
                for (int i = 0; i < headMap.size(); i++) {
                    headers.add(headMap.get(i));
                }
            }

            @Override
            public void invoke(Map<Integer, String> data, AnalysisContext context) {
                // 处理每一行数据
                Map<String, Object> rowMap = new HashMap<>();
                for (int i = 0; i < headers.size(); i++) {
                    rowMap.put(headers.get(i), data.get(i));
                    //rowMap.put("Column" +i, data.get(i));
                }
                dataList.add(rowMap);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 所有数据解析完成后的操作
            }
        };

        try {
            // 使用 EasyExcel 读取文件
            InputStream is = file.getInputStream();
            EasyExcel.read(is, listener).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
            //System.err.println("解析 Excel 文件时出错: " + e.getMessage());
        }

        return dataList;
    }

    private boolean isRowEmpty(Row row) {
        if (row == null) return true;
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
            Cell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != CellType.BLANK) {
                return false;
            }
        }
        return true;
    }

    private Object getCellValue(Cell cell) {
        Object value = null;
        switch (cell.getCellType()) {
            case STRING:
                value = cell.getStringCellValue();
                break;
            case NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    value = cell.getDateCellValue();
                } else {
                    value = cell.getNumericCellValue();
                }
                break;
            case BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case FORMULA:
                value = cell.getCellFormula();
                break;
            default:
                break;
        }
        return value;
    }

    @Override
    public List<ZXGL_XiangMuLiXiang_MingXiEntity> GetZXGL_XiangMuLiXiang_XianmguIdAndName(List<String> xmmc) {
        QueryWrapper<ZXGL_XiangMuLiXiang_MingXiEntity> queryWrapper = new QueryWrapper<>();
        for (int i = 0; i < xmmc.size(); i++) {
            String xmmcName = xmmc.get(i);
            queryWrapper.lambda().eq(ZXGL_XiangMuLiXiang_MingXiEntity::getXmmc, xmmcName).select(ZXGL_XiangMuLiXiang_MingXiEntity::getXmbh, ZXGL_XiangMuLiXiang_MingXiEntity::getMainid, ZXGL_XiangMuLiXiang_MingXiEntity::getXmmc);
        }
        return zXGL_XiangMuLiXiang_MingXiService.list(queryWrapper);
    }

    /**
     * 获取某个分类中的下拉框的值
     *
     * @param parentId
     * @return
     */
    public List<Map<String, String>> getDictionaryData(String parentId) {
        List<Map<String, String>> result = new ArrayList<>();
        List<Map<String, String>> queryResult = baseMapper.getDictionaryDataByParentId(parentId);
        for (Map<String, String> row : queryResult) {
            Map<String, String> mappedRow = new HashMap<>();
            mappedRow.put(row.get("F_FullName"), row.get("F_Id"));
            result.add(mappedRow);
        }
        return result;
    }

    public String getFIdByFullName(String parentId, String fullName) {
        List<Map<String, String>> data = getDictionaryData(parentId);
        for (Map<String, String> row : data) {
            if (row.containsKey(fullName)) {
                return row.get(fullName);
            }
        }
        return null;
    }
}